package heap;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 实现堆的基础操作
 * User: 王圆豪
 * Date: 2024-09-18
 * Time: 18:33
 */
public class TestHeap {
    int[] elem;
    int usedSize;

    public TestHeap(int[] elem) {
        this.elem = elem;
        this.usedSize = elem.length;
    }

    //向下调整为大根堆
    public void sitDown() {
        for (int i = (usedSize - 2) / 2; i >= 0; i--) {
            int parent = i;
            int leftChild = parent * 2 + 1;
            while (leftChild < usedSize){
                if (leftChild + 1 < usedSize && elem[leftChild + 1] > elem[leftChild])
                    leftChild++;
                if (elem[leftChild] > elem[parent]) {
                    swap(elem, leftChild, parent);
                }
                parent = leftChild;
                leftChild = parent * 2 + 1;
            }
        }
    }

    //向上调整为大根堆
    public void sitUp() {
        for (int i = 1; i < usedSize; i++) {
            int child = i;
            int parent = (child - 1) / 2;
            while (child > 0){
                if (elem[child] > elem[parent]){
                    swap(elem, child, parent);
                }
                child = parent;
                parent = (child - 1) / 2;
            }
        }
    }

    //头删
    public int poll() {
        int result = elem[0];
        swap(elem, 0, usedSize - 1);
        usedSize--;
        sitDown();
        return result;
    }

    //尾插
    public void offer(int k) {
        if (isFull()){
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[usedSize] = k;
        usedSize++;
        sitUp();
    }

    //判断数组满不满
    private boolean isFull() {
        return usedSize == elem.length;
    }

    //交换
    private void swap(int[] elem, int a, int b) {
        int t = elem[a];
        elem[a] = elem[b];
        elem[b] = t;
    }

    //判断是否为空
    public boolean isEmpty(){
        return usedSize == 0;
    }

    //获取堆顶元素
    public int peekHeap(){
        return elem[0];
    }
}
